package com.volcengine.iam;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.volcengine.model.request.AssumeRoleRequest;
import com.volcengine.model.response.AssumeRoleResponse;
import com.volcengine.service.sts.ISTSService;
import com.volcengine.service.sts.impl.STSServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@Slf4j
public class GetSessionToken {
    @RequestMapping("/getSTS")
    public String getSTS() throws Exception {
        String ak = "AKLTZjEwMTA3YjIyMDVmNGEzN2E2MmIyNjQ2YzA0YTNjNTY";
        String sk = "TkRkbU1XTXdaR0ZpWTJGbU5EUXhOR0kzWTJVelkyTmhNelF5WkdRNE5tTQ==";
        String region = "cn-beijing";

        AssumeRoleResponse resp = getRoleResponse(ak, sk, region);
        System.out.println(JSON.toJSONString(resp));
        String sessionToken = resp.getResult().getCredentials().getSessionToken();
        String accessKeyId = resp.getResult().getCredentials().getAccessKeyId();
        String secretAccessKey = resp.getResult().getCredentials().getSecretAccessKey();
        log.info("Get IAM SessionToken: " + sessionToken);

        // 发送POST请求
        String url = "https://console.volc-embed.com/api/passport/login/getSigninTokenWithSTS";
        String httpResp = httpPost(url, accessKeyId, secretAccessKey, sessionToken);
        ObjectMapper objectMapper = new ObjectMapper();
        // 将 JSON 字符串转换为 JsonNode 对象
        JsonNode jsonNode = objectMapper.readTree(httpResp);
        // 获取特定字段的值
        log.info("SinginToken result：" + httpResp);
        String signinToken = jsonNode.get("Result").get("SigninToken").asText();
        return "SessionToken：" + sessionToken + "\n" + "SigninToken：" + signinToken;
    }

    private static AssumeRoleResponse getRoleResponse(String ak, String sk, String region) throws Exception {
        ISTSService stsService = STSServiceImpl.getInstance();

        stsService.setAccessKey(ak);
        stsService.setSecretKey(sk);
        stsService.setRegion(region);

        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setRoleSessionName("tls_iframe");
        request.setDurationSeconds(900);
        request.setRoleTrn("trn:iam::2100005224:role/tls_iframe");
        return stsService.assumeRole(request);
    }

    public static String httpPost(String url, String ak, String sk, String sessionToken) {
        RestTemplate restTemplate = new RestTemplate();
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        // 设置请求参数
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
        map.add("accessKeyId", ak);
        map.add("secretAccessKey", sk);
        map.add("sessionToken", sessionToken);
        // 将请求头和请求参数封装到HttpEntity中
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        // 发送POST请求
        return restTemplate.postForObject(url, request, String.class);
    }
}
